package com.jkgh.remedium.rsgen.generator.flash;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import com.jkgh.remedium.rsgen.vo.DataObject;
import com.jkgh.remedium.rsgen.vo.MethodObject;
import com.jkgh.remedium.rsgen.vo.RemediumSystem;

public class RemediumSystemFlashGenerator {

	public static void generate(File outputDir, RemediumSystem rs) throws FileNotFoundException {

		String packagePath = rs.getPackageName().replace('.', '/');
		outputDir = new File(outputDir, packagePath);
		outputDir.mkdirs();
		deleteContents(outputDir);

		File systemOutputDir = new File(outputDir, "system");
		systemOutputDir.mkdir();

		generate(new File(systemOutputDir, rs.getName() + "RemediumSystem.as"), rs.getName(), rs.getPackageName(), rs.getAccessClass());

		for (DataObject d : rs.getDataObjects()) {
			RemediumDataObjectFlashGenerator.generate(outputDir, d, rs.getPackageName());
		}

		for (MethodObject m : rs.getMethodObjects()) {
			RemediumMethodObjectFlashGenerator.generate(outputDir, m, rs.getPackageName());
		}
	}

	private static void generate(File systemOutput, String systemName, String packageName, String accessClass) throws FileNotFoundException {

		PrintWriter out = new PrintWriter(systemOutput);

		out.println("package " + packageName + ".system {");
		out.println();
		out.println("	import com.jkgh.remedium.RemediumSystem;");
		out.println("	import com.jkgh.remedium.objects.messages.RemediumInMessage;");
		out.println("	import com.jkgh.remedium.states.OrderAwaitingState;");
		out.println("	import com.jkgh.remedium.test.Main;");
		out.println("	import " + packageName + "." + accessClass + ";");
		out.println();
		out.println("	import flash.net.Socket;");
		out.println();
		out.println("	public class " + systemName + "RemediumSystem extends RemediumSystem {");
		out.println();
		out.println("		public function " + systemName + "RemediumSystem(serverIP:String, onMainObjectReceived:Function) {");
		out.println("			super(serverIP, " + accessClass + ".createConsumingState(new RemediumInMessage(), function(result:" + accessClass + "):void {");
		out.println("				setState(new OrderAwaitingState());");
		out.println("				onMainObjectReceived(result);");
		out.println("			}));");
		out.println("		}");
		out.println("	}");
		out.println("}");

		out.close();
	}

	private static void deleteContents(File dir) {

		for (File f : dir.listFiles()) {
			if (f.isDirectory()) {
				deleteContents(f);
			}
			f.delete();
		}
	}
}
